package com.dailyblue.java.cloud.sentinel.consumer.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.dailyblue.java.cloud.sentinel.consumer.handler.BlockExceptionHandler;
import com.dailyblue.java.cloud.sentinel.consumer.handler.FallbackHandler;
import com.dailyblue.java.cloud.sentinel.consumer.service.ConsumerService;
import com.dailyblue.java.commons.util.DateUtil;
import com.dailyblue.java.commons.util.JsonResult;
import com.dailyblue.java.commons.util.ResultTool;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@RestController
@RequestMapping("/consumer")
@Slf4j
public class ConsumerController {
    @Resource
    private ConsumerService consumerService;

    @GetMapping("/a")
    public JsonResult a() {
        return consumerService.a();
    }

    @GetMapping("/b")
    public JsonResult b() {
        return consumerService.b();
    }

    @GetMapping("/c")
    public JsonResult c() {
        log.info("{}时间接收了请求", DateUtil.getNowDate());
        return consumerService.c();
    }

    @GetMapping("/d")
    public JsonResult d() {
        log.info("d");
        return consumerService.c();
    }

    @GetMapping("/e")
    public JsonResult e() {
        int random = (int) (Math.random() * 3);
        log.info("num:{}", random);
        int result = 10 / random;
        return ResultTool.success("This is e method!" + result);
    }

    @GetMapping("/f")
    @SentinelResource("messageF")
    public JsonResult f(int a) {
        log.info("传递进来的参数是：{}", a);
        return ResultTool.success("This is f method!a:" + a);
    }

    @GetMapping("/g")
    public JsonResult g(String server) {
        log.info("进入了g方法，传递进来的参数是：{}", server);
        return ResultTool.success("This is g method!server:" + server);
    }

    @GetMapping("/h1")
    @SentinelResource(value = "h1",
            blockHandler = "h1", blockHandlerClass = BlockExceptionHandler.class,
            fallback = "h1", fallbackClass = FallbackHandler.class)
    public JsonResult h1(String server) {
        log.info("进入了h1方法，接收的参数是：{}", server);
        int a = 10 / ((int) (Math.random() * 2));
        return ResultTool.success("h1 successful");
    }

    public JsonResult h2(String server, BlockException e) {
        log.info("进入了h2方法，这个是一个block异常处理方法,{}，接收的参数是：{}", e.getMessage(), server);
        return ResultTool.fail("h2 fail");
    }

    public JsonResult h3(String server, Throwable e) {
        log.info("进入了h3方法，这个是一个Throwable异常处理方法,{}，接收的参数是：{}", e.getMessage(), server);
        return ResultTool.fail("h3 fail");
    }

}
